<?php

namespace App\Http\Controllers\Admin;

use App\Models\Region;
use App\Services\Admin\RegionService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class RegionController extends Controller
{
    protected $service;

    public function __construct(RegionService $regionService)
    {
        $this->service = $regionService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin.region.index');
    }

    public function data(Request $request)
    {
        $res = Region::where('parent_id',$request->get('parent_id',0))->orderBy('id','desc')->orderBy('sort','desc')->paginate($request->get('limit',30))->toArray();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return response()->json($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $id = $request->get('id')??0;
        if ($id) {
            $region = $this->service->getRegionById($id);
            $level = $region->level + 1;
        }else{
            $level = 0;
            $region = '';
        }
//        $categorys = $this->tree(Region::get()->toArray());
        return view('admin.region.create',compact('level','id','region'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'name'  => 'required|string',
            'sort'  => 'required|numeric',
            'parent_id' => 'required|numeric'
        ]);
        $data = $request->all();
        if(isset($data['map'])){
            $map = explode(',',$data['map']);
            $data['longitude'] = $map[0];
            $data['latitude'] = $map[1];
        }
        if (Region::create($data)){
            return redirect(route('admin.region'))->with(['status'=>'添加完成']);
        }
        return redirect(route('admin.region'))->with(['status'=>'系统错误']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $category = $this->service->getRegionById($id);
        $level = $category->level;
        if($category->parent_id){
            $region = $this->service->getRegionById($category->parent_id);
        }else{
            $region = '';
        }
//        $categorys = $this->tree(Category::get()->toArray());
        return view('admin.region.edit',compact('category','id','region','level'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'name'  => 'required|string',
            'sort'  => 'required|numeric',
            'parent_id' => 'required|numeric'
        ]);
        $data = $request->all();
        if(isset($data['map'])){
            $map = explode(',',$data['map']);
            $data['longitude'] = $map[0];
            $data['latitude'] = $map[1];
        }
        $category = Region::findOrFail($id);
        if ($category->update($data)){
            return redirect(route('admin.region'))->with(['status'=>'更新成功']);
        }
        return redirect(route('admin.region'))->withErrors(['status'=>'系统错误']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)){
            return response()->json(['code'=>1,'msg'=>'请选择删除项']);
        }
        $category = Category::with(['childs','articles'])->find($ids);
        if (!$category){
            return response()->json(['code'=>1,'msg'=>'请选择删除项']);
        }
        if (!$category->childs->isEmpty() || !$category->articles->isEmpty()){
            return response()->json(['code'=>1,'msg'=>'该分类下有子分类或者文章，不能删除']);
        }
        if ($category->delete()){
            return response()->json(['code'=>0,'msg'=>'删除成功']);
        }
        return response()->json(['code'=>1,'msg'=>'删除失败']);
    }

    public function getCity(Request $request)
    {
        $reg = explode(',',$request->input('province_id'));
        $data = $this->service->getCityById($reg[0]);
        if (count($data)){
            return response()->json([
                'data' => $data,
                'status' => 'T'
            ]);
        }else{
            return response()->json([
                'status' => 'F'
            ]);
        }
    }
}
